package com.example.keli.ui.userinfo;

import android.content.Context;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.text.Html;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.keli.R;
import com.example.keli.api.HttpUtils;
import com.example.keli.api.RetrofitManager;
import com.example.keli.api.http.api.BaseResponse;
import com.example.keli.api.http.api.subscriber.SubscriberListener;
import com.example.keli.base.BaseActivity;
import com.example.keli.base.app.C;
import com.example.keli.base.utils.AlbumUtil;
import com.example.keli.base.utils.GlideUtil;
import com.example.keli.base.utils.LogUtils;
import com.example.keli.base.utils.ToastUtil;
import com.example.keli.base.widget.NoScrollGridView;
import com.flyco.roundview.RoundTextView;
import com.qiniu.android.http.ResponseInfo;
import com.qiniu.android.storage.Configuration;
import com.qiniu.android.storage.UpCompletionHandler;
import com.qiniu.android.storage.UploadManager;
import com.yanzhenjie.album.Action;
import com.yanzhenjie.album.AlbumFile;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * description: 我要报名，上传视频界面
 * author: Allen
 * date: 2019/3/25 15:13
 */
public class ApplyActivity extends BaseActivity {

    @BindView(R.id.gridview)
    NoScrollGridView gridview;
    @BindView(R.id.local_video)
    ImageView localVideo;
    @BindView(R.id.live_record)
    ImageView liveRecord;
    @BindView(R.id.sign)
    EditText sign;
    @BindView(R.id.commit)
    RoundTextView commit;
    @BindView(R.id.suijishu)
    TextView suijishu;

    private ImageGridAdapter mImageGridAdapter;
    String video = "";//上传的视频地址
    String verify_video = "";//录制的视频上传成功后的地址
    String img = "";//上传成功后的图片地址，多张用，分隔
    String aaid = "";//报名的aaid

    public static void start(Context context, String aaid) {
        Intent intent = new Intent(context, ApplyActivity.class);
        intent.putExtra("aaid", aaid);
        context.startActivity(intent);
    }

    @Override
    protected int layoutId() {
        return R.layout.activity_apply;
    }

    @Override
    protected void bindData() {
        abTitle.setText("上传视频/图片");
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayShowTitleEnabled(false);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        mImageGridAdapter = new ImageGridAdapter();
        gridview.setAdapter(mImageGridAdapter);
        aaid = getIntent().getStringExtra("aaid");

        EventBus.getDefault().register(this);


        String strRand="" ;
        for(int i=0;i<3;i++){
            strRand += String.valueOf((int)(Math.random() * 10)) ;
        }
        suijishu.setText(Html.fromHtml("请录制并上传一个本人正脸并读出" + "<font color='#FF0000'>" + strRand +"</font>"+"数字的验证视频"));
    }

    private void upImagetokens(final String path) {
        RetrofitManager.ApiFunc(RetrofitManager.mApiFunc.uptokens(), new SubscriberListener<BaseResponse<String>>() {
            @Override
            public void onSuccess(BaseResponse<String> response) {
                Configuration config = new Configuration.Builder()
                        .dns(null)
                        .build();
                String key = String.valueOf(System.currentTimeMillis());
                UploadManager uploadManager = new UploadManager(config);
                uploadManager.put(path, key, response.getData(),
                        new UpCompletionHandler() {
                            @Override
                            public void complete(String key, ResponseInfo info, JSONObject res) {
                                //res包含hash、key等信息，具体字段取决于上传策略的设置
                                if (info.isOK()) {
                                    LogUtils.loge("qiniu", "Upload Success");
                                    LogUtils.loge("地址是多少>>>>>" + C.Constance.IMAGE_HOST + key + "?imageslim");
                                    //上传文件的标记，1是图片，2是视频，3是录制视频
                                    String url = C.Constance.IMAGE_HOST + key + "?imageslim";
                                    ImageUploadBean imageUploadBean = new ImageUploadBean();
                                    imageUploadBean.setUrl(url);
                                    mPicList.add(imageUploadBean);
                                    mImageGridAdapter.notifyDataSetChanged();
                                    if (albumFiles.size() > 0) {
                                        albumFiles.remove(0);
                                        if (albumFiles.size() == 0) {
                                            stopProgressDialog();
                                            return;
                                        }
                                    }
                                    if (albumFiles.size() > 0) {
                                        //上传
                                        EventBus.getDefault().post(new UpImage());
                                    }
                                } else {
                                    LogUtils.loge("qiniu", "Upload Fail");
                                    //如果失败，这里可以把info信息上报自己的服务器，便于后面分析上传错误原因
                                }
                            }
                        }, null);
            }

            @Override
            public void onFailer(String msg) {
                stopProgressDialog();
                ToastUtil.show(msg);
            }

            @Override
            public void onTokenError() {
            }
        });
    }

    private void uptokens(final String path, final int flag) {
        startProgressDialog();
        RetrofitManager.ApiFunc(RetrofitManager.mApiFunc.uptokens(), new SubscriberListener<BaseResponse<String>>() {
            @Override
            public void onSuccess(BaseResponse<String> response) {
                Configuration config = new Configuration.Builder()
                        .dns(null)
                        .build();
                String key = String.valueOf(System.currentTimeMillis());
                UploadManager uploadManager = new UploadManager(config);
                uploadManager.put(path, key, response.getData(),
                        new UpCompletionHandler() {
                            @Override
                            public void complete(String key, ResponseInfo info, JSONObject res) {
                                stopProgressDialog();
                                //res包含hash、key等信息，具体字段取决于上传策略的设置
                                if (info.isOK()) {
                                    LogUtils.loge("qiniu", "Upload Success");
                                    LogUtils.loge("地址是多少>>>>>" + C.Constance.IMAGE_HOST + key + "?imageslim");
                                    //上传文件的标记，1是图片，2是视频，3是录制视频
                                    String url = C.Constance.IMAGE_HOST + key + "?imageslim";
                                    switch (flag) {
                                        case 1:
                                            ImageUploadBean imageUploadBean = new ImageUploadBean();
                                            imageUploadBean.setUrl(url);
                                            mPicList.add(imageUploadBean);
                                            mImageGridAdapter.notifyDataSetChanged();
                                            break;
                                        case 2:
                                            video = url;
                                            GlideUtil.displayFile(getActivity(), localVideo, path);
                                            break;
                                        case 3:
                                            verify_video = url;
                                            GlideUtil.displayFile(getActivity(), liveRecord, path);
                                            break;
                                    }
                                } else {
                                    LogUtils.loge("qiniu", "Upload Fail");
                                    //如果失败，这里可以把info信息上报自己的服务器，便于后面分析上传错误原因
                                }
                            }
                        }, null);
            }

            @Override
            public void onFailer(String msg) {
                stopProgressDialog();
                ToastUtil.show(msg);
            }

            @Override
            public void onTokenError() {
            }
        });
    }

    @OnClick({R.id.local_video, R.id.live_record, R.id.commit})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.local_video:
                AlbumUtil.getVideos(getActivity(), 31000, new Action<ArrayList<AlbumFile>>() {
                    @Override
                    public void onAction(@NonNull ArrayList<AlbumFile> result) {
                        //选择30秒内的视频文件上传
                        uptokens(result.get(0).getPath(), 2);
                    }
                });
                break;
            case R.id.live_record:
                AlbumUtil.recordVideo(getActivity(), 15000, new Action<String>() {
                    @Override
                    public void onAction(@NonNull String result) {
                        uptokens(result, 3);
                    }
                });
                break;
            case R.id.commit:
                if (mPicList.size() < 5) {
                    ToastUtil.show("最少上传5张图片");
                    return;
                } else if (TextUtils.isEmpty(video)) {
                    ToastUtil.show("请上传视频");
                    return;
                } else if (TextUtils.isEmpty(verify_video)) {
                    ToastUtil.show("请录制视频");
                    return;
                }
                sign();
                break;
        }
    }

    public class ViewHolder {
        public ImageView image_delete;
        public ImageView imageview;
        public TextView cover;
    }

    // 最大图片数量
    private int mMaxCount = 8;
    //存储选择的图片数据//最终上传的图片地址，最多8张。逗号隔开
    private List<ImageUploadBean> mPicList = new ArrayList<>();
    //用于记录规格图的角标
    private int spec_position = 0;
    //用于记录主图的角标
    private int cover_position = 0;
    //选择的图片，每次选择中的
    private ArrayList<AlbumFile> albumFiles = new ArrayList<>();

    public class ImageGridAdapter extends BaseAdapter {

        public int getCount() {
            return mPicList.size() + 1;
        }

        public Object getItem(int arg0) {
            return null;
        }

        public long getItemId(int arg0) {
            return 0;
        }

        /**
         * GridView Item设置
         */
        public View getView(final int position, View convertView, ViewGroup parent) {
            ViewHolder holder = null;
            if (convertView == null) {
                convertView = getLayoutInflater().inflate(R.layout.item_image_grid_layout, parent, false);
                holder = new ViewHolder();
                holder.image_delete = convertView.findViewById(R.id.delete);
                holder.imageview = convertView.findViewById(R.id.imageview);
                holder.cover = convertView.findViewById(R.id.cover);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            if (position == mMaxCount) {
                holder.imageview.setVisibility(View.GONE);
                holder.image_delete.setVisibility(View.GONE);
            } else {
                holder.imageview.setVisibility(View.VISIBLE);
                holder.image_delete.setVisibility(View.VISIBLE);
            }
            if (position == mPicList.size()) {
                holder.image_delete.setVisibility(View.GONE);
                GlideUtil.display(getActivity(), holder.imageview, R.mipmap.ic_upload);
                holder.cover.setVisibility(View.GONE);
                holder.imageview.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        //添加图片
                        if (mPicList.size() >= 8) {
                            ToastUtil.show("最多上传8张图片");
                            return;
                        }
                        AlbumUtil.getImages(getActivity(), mMaxCount - mPicList.size(), new Action<ArrayList<AlbumFile>>() {
                            @Override
                            public void onAction(@NonNull ArrayList<AlbumFile> result) {
                                if (result.size() > 0) {
                                    //上传图片
//                                    uptokens(result.get(0).getPath(), 1);
                                    albumFiles = result;
                                    startProgressDialog();
                                    upImagetokens(result.get(0).getPath());
                                }
                            }
                        });
                    }
                });
            } else {
                holder.image_delete.setVisibility(View.VISIBLE);
                if (cover_position == position) {
                    holder.cover.setVisibility(View.VISIBLE);
                } else {
                    holder.cover.setVisibility(View.GONE);
                }
                if (TextUtils.isEmpty(mPicList.get(position).getUrl())) {
                    GlideUtil.displayFile(getActivity(), holder.imageview, mPicList.get(position).getPath());
                } else {
                    GlideUtil.display(getActivity(), holder.imageview, mPicList.get(position).getUrl());
                }
                holder.imageview.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        mPicList.get(cover_position).setCover(0);
                        cover_position = position;
                        //指定封面
                        mPicList.get(position).setCover(1);
                        notifyDataSetChanged();
                    }
                });
            }

            holder.image_delete.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    //删除
                    if (mPicList.get(position).getCover() == 1) {
                        cover_position = 0;
                    }
                    mPicList.remove(position);
                    notifyDataSetChanged();
                }
            });

            return convertView;
        }

    }


    private void sign() {
        startProgressDialog();
        img = "";
        ImageUploadBean urlOne = mPicList.get(cover_position);
        mPicList.remove(cover_position);
        mPicList.add(0, urlOne);
        int size = mPicList.size();
        for (int i = 0; i < size; i++) {
            if (i == (size - 1)) {
                img = img + mPicList.get(i).getUrl();
            } else {
                img = img + mPicList.get(i).getUrl() + ",";
            }
        }
        Map<String, String> map = new HashMap<>();
        map.put("aaid", aaid);
        map.put("img", img);
        map.put("video", video);
        map.put("verify_video", verify_video);
        map.put("content", sign.getText().toString());
        HttpUtils.ApiFunc(RetrofitManager.mApiFunc.sign(map), new SubscriberListener<BaseResponse<Object>>() {
            @Override
            public void onSuccess(BaseResponse<Object> objectBaseResponse) {
                stopProgressDialog();
                ToastUtil.show("报名成功");
                EventBus.getDefault().post(C.EVENT.SIGN_SUCCESS);
                finish();
            }

            @Override
            public void onFailer(String msg) {
                stopProgressDialog();
                ToastUtil.show(msg);
            }

            @Override
            public void onTokenError() {

            }
        });
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void upLoadImage(UpImage upImage) {
        upImagetokens(albumFiles.get(0).getPath());
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

}
